from django_redis import get_redis_connection
from rest_framework import serializers


class ImageCodeSerializer(serializers.Serializer):
    ''' 比较图形验证码的序列化器 '''
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4, min_length=4)

    def validate(self, attrs):
        '''联合校验'''
        # 先从attrs中取到参数
        image_code_id = attrs['image_code_id']
        text = attrs['text']
        # 从redis中获取真实的图片验证码的内容
        redis_conn = get_redis_connection('verify_codes')
        image_code_text = redis_conn.get('img_%s'% image_code_id)
        print(image_code_text)
        if not image_code_text:
            raise serializers.ValidationError('图形验证码已过期')
        # 删除redis中存储的图片验证码信息
        redis_conn.delete('img_%s'% image_code_id)
        # 校验用户传过来的图形验证码内容和真实存储内容
        # python3中redis查询出来的数据都是byte格式的，需要解码
        image_code_text = image_code_text.decode()
        if text.lower() != image_code_text.lower():
            raise serializers.ValidationError('图形验证码输入错误')
        # 判断是否在60s内
        mobile = self.context['view'].kwargs['mobile']
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            raise serializers.ValidationError('请求次数过于频繁')
        return attrs


